var router = require('koa-router')()
var db = require('../utils/mysql.js');
/* GET users listing. */
router.get('/toAdd', ctx=>{
  ctx.render('publish/add.html' ,{title:'发表博客'});
});
router.get('/toDetail/:id/:link',async ctx=> {
  var id =ctx.params.id;
  var link = ctx.params.link;
  var sql = "select a.id,a.title,a.content,a.create_id createId,a.create_time createTime,b.show_name userName from blog_publish a left join blog_user b on a.create_id=b.id where a.id=:id";
  const result = await db.query(sql,{id:id});
  if(result.length>0){
    result[0].link = link;
    ctx.render('publish/detail.html' ,result[0]);
  }
});
router.post('/add',async ctx=> {
	// 新增用户
  const data = ctx.request.body;
  var title = data.title;
  if(!title){
     // ctx.flash('error','标题不能为空');
     ctx.redirect('./add');
     return ;
  }
  var user = JSON.parse(ctx.cookies.get('user')||'{}');
  if(!user.id){
     // ctx.flash('error','用户登录超时');
     ctx.redirect('/home');
     return ;
  }
  var sql = "insert into blog_publish(title,content,create_id) values (:title,:content,:createId)";
  const result = await db.query(sql,{title:title,content:data.content,createId:user.id});
  if(result.insertId){
    // ctx.flash('success','发表成功');
    console.log('发表成功');
    ctx.redirect('/home');
  }
});
router.get('/', ctx=> {
  ctx.body='respond with a publish';
});

module.exports = router;
